//
//  HJUserInfoController.m
//  KaiChat
//
//  Created by lx on 2023/10/20.
//

#import "HJUserInfoController.h"
#import "HJIM.h"
#import "HJChatController.h"
#import "HJErrorTipView.h"
#import "HJSingleChatSettingController.h"

@interface HJUserInfoController ()

@property (nonatomic, weak) UILabel *remarksLabel;
@property (nonatomic, weak) UILabel *nicknameLabel;
@property (nonatomic, weak) UILabel *userIdLabel;
@property (nonatomic, weak) UILabel *signatureLabel;
@property (nonatomic, weak) UILabel *locationLabel;
@property (nonatomic, weak) UIImageView *avatarImageView;
@property (nonatomic, weak) HJStyle2Button *sendMessageButton;
@property (nonatomic, weak) HJStyle1Button *applyAddButton;
@property (nonatomic, strong) HJChatUserModel *userModel;
@property (nonatomic, weak) HJErrorTipView *tipView;
@property (nonatomic, weak) UIView *lineView;
@property (nonatomic, weak) UIImageView *genderImageView;
@property (nonatomic, weak) UIView *headerView;

@end

@implementation HJUserInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"Info";
    self.navigationBar.alpha = 0;
    self.navigationBar.lineView.hidden = YES;
    if (!TJIM_isSelf(self.userId)) {
        self.navigationBar.rightBarButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"singleChat_icon"] target:self action:@selector(didClickSettingButton)];
        self.navigationBar.rightBarButton.hidden = YES;
    }
    
    UIImageView *topBackgroundImageView = [UIImageView addToView:self.view];
    topBackgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    topBackgroundImageView.image = [UIImage imageWithContentsOfName:@"user_top_bg" type:@"png"];
    CGFloat imageH = topBackgroundImageView.image.size.height * KScreenWidth / topBackgroundImageView.image.size.width;
    [topBackgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(imageH);
    }];
    
    
    UIView *headerView = [UIView addToView:self.view];
    headerView.hidden = YES;
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(98);
        make.top.offset(KNavBarHight);
    }];
    
    UIImageView *avatarImageView = [UIImageView addToView:headerView];
    avatarImageView.addCornerRadius(29);
    avatarImageView.image = [UIImage imageNamed:defaultAvatarName];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.width.height.offset(58);
        make.centerY.offset(0);
    }];
    
    UIImageView *genderImageView = [UIImageView addToView:headerView];
    [genderImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(avatarImageView);
        make.width.height.offset(18);
    }];
    
    //
    //    UILabel *remarksLabel = [UILabel lableWithSuperView:headerView font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:nil textAlignment:NSTextAlignmentLeft];
    //    [remarksLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(avatarImageView).offset(4);
    //        make.left.equalTo(avatarImageView.mas_right).offset(10);
    //    }];
    //
    UILabel *nicknameLabel = [UILabel lableWithSuperView:headerView font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:nil textAlignment:NSTextAlignmentLeft];
    [nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(avatarImageView).offset(10);
        make.left.equalTo(avatarImageView.mas_right).offset(10);
        make.right.mas_lessThanOrEqualTo(-leftRightMargin);
    }];
    
    UILabel *userIdLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(12) color:UIColor.tj_868391Color title:nil textAlignment:NSTextAlignmentLeft];
    [userIdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nicknameLabel.mas_bottom).offset(6);
        make.left.equalTo(nicknameLabel);
    }];
    
    UILabel *locationLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:nil textAlignment:NSTextAlignmentLeft];
    [locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userIdLabel.mas_bottom).offset(6);
        make.left.equalTo(nicknameLabel);
    }];
    
    UIView *lineView = [UIView addToView:headerView];
    lineView.hidden = YES;
    lineView.backgroundColor = UIColor.tj_F3F2F7Color;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.height.offset(1);
        make.bottom.offset(0);
    }];
    
    UILabel *signatureLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(14) color:UIColor.tj_868391Color title:nil textAlignment:NSTextAlignmentLeft];
    signatureLabel.numberOfLines = 0;
    [signatureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_bottom).offset(20);
        make.left.right.inset(leftRightMargin);
    }];
    
    HJStyle2Button *sendMessageButton = [HJStyle2Button buttonWithSuperView:self.view font:UIFontMediumMake(14) color:nil title:@"Send message"];
    sendMessageButton.hidden = YES;
    [sendMessageButton addTarget:self action:@selector(didClickSendMessageButton) forControlEvents:UIControlEventTouchUpInside];
    [sendMessageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(20);
        make.height.offset(55);
        make.bottom.inset(10 + TabbarSafeBottomMargin);
    }];
    
    HJStyle1Button *applyAddButton = [HJStyle1Button buttonWithSuperView:self.view font:UIFontMediumMake(14) color:nil title:@"Add Friends"];
    applyAddButton.hidden = YES;
    [applyAddButton addTarget:self action:@selector(didClickApplyAddButton) forControlEvents:UIControlEventTouchUpInside];
    [applyAddButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.bottom.equalTo(sendMessageButton);
    }];
    
    HJErrorTipView *tipView = [[HJErrorTipView alloc] initWithText:@"This user has been blocked. You will not receive any messages from them." showCloseButton:NO];
    tipView.hidden = YES;
    [self.view addSubview:tipView];
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(20);
        make.height.offset(52);
        make.bottom.inset(10 + TabbarSafeBottomMargin + 85);
    }];
    
    _genderImageView = genderImageView;
    _tipView = tipView;
    _sendMessageButton = sendMessageButton;
    _applyAddButton = applyAddButton;
    _signatureLabel = signatureLabel;
    //    _remarksLabel = remarksLabel;
    _locationLabel = locationLabel;
    _nicknameLabel = nicknameLabel;
    _userIdLabel = userIdLabel;
    _avatarImageView = avatarImageView;
    _lineView = lineView;
    _headerView = headerView;
    
    if (_Uid) {
        dispatch_async_sql_queue(^{
            HJChatUserModel *model = [HJIM.shareIM.userManager queryUserInfoByUid:self.Uid];
            dispatch_async_main_queue(^{
                if (model) {
                    [self handleUserData:model];
                    self.userId = model.userId;
                    [self loadDataIsNetwork:YES isCache:YES];
                } else {
                    [HJIM.shareIM.userManager searchFridendWithKeyword:self.Uid complete:^(HJChatUserModel * _Nullable model) {
                        self.userId = model.userId;
                        [self loadDataIsNetwork:YES isCache:YES];
                    }];
                }
            });
        });
    } else {
        [self loadDataIsNetwork:YES isCache:YES];
    }
}

- (void)didClickSettingButton {
    HJSingleChatSettingController *groupSettingController = [[HJSingleChatSettingController alloc] init];
    groupSettingController.userId = self.userId;
    [groupSettingController setSetBlocklistComplete:^(BOOL isBlocklist) {
        self.tipView.hidden = !isBlocklist;
    }];
    [self.navigationController pushViewController:groupSettingController];
}

- (void)didClickSendMessageButton {
    HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithSessionId:toString(self.userModel.sessionId) sessionUserd:toString(self.userModel.userId) chatType:HJChatTypeSingle sessionName:self.userModel.showName];
    [HJChatController showWithSessionModel:sessionModel];
}

- (void)didClickApplyAddButton {
    if (_userModel.relationship == -1 || _userModel.relationship == 3 || (_userModel.relationship == 2 && _userModel.way == 2)) {
        [HJHUD showGraceTimeLoadingInView:self.view];
        [HJIM.shareIM.userManager sendApplyAddFriendWithUserId:self.userModel.userId complete:^(NSError * _Nullable error) {
            if (!error) {
                if (self.applySucceed) {
                    self.applySucceed();
                }
                [self loadDataIsNetwork:YES isCache:NO];
            }
        }];
    }
}

- (void)handleUserData:(HJChatUserModel *)model {
    
    dispatch_async_sql_queue(^{
        HJChatSessionModel *sessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:model.sessionId];
        if (sessionModel) {
            sessionModel.sessionUid = sessionModel.uid;
            sessionModel.sessionUserd = model.userId;
            sessionModel.sessionName = model.showName;
            [sessionModel bg_saveOrUpdate];
        }
    });
    
    self.userModel = model;
    self.lineView.hidden = NO;
    self.headerView.hidden = NO;
    
    if (model.isFridend) {
        self.sendMessageButton.hidden = NO;
        self.applyAddButton.hidden = YES;
        self.navigationBar.rightBarButton.hidden = NO;
    } else if (model.relationship == -1 || model.relationship == 3) {
        self.sendMessageButton.hidden = YES;
        self.applyAddButton.hidden = NO;
    } else if (model.relationship == 2) {
        self.sendMessageButton.hidden = YES;
        if (model.way == 1) {//自己发起的
            [self.applyAddButton setTitle:@"Waiting" forState:UIControlStateNormal];
            self.applyAddButton.enabled = NO;
            [self.applyAddButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        } else {
            [self.applyAddButton setTitle:@"Add Friends" forState:UIControlStateNormal];
            [self.applyAddButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
            self.applyAddButton.enabled = YES;
        }
        self.applyAddButton.hidden = NO;
    } else if (model.relationship == 0) {
        self.sendMessageButton.hidden = NO;
        self.applyAddButton.hidden = YES;
    } else if (model.relationship == 4) {
       self.sendMessageButton.hidden = NO;
       self.applyAddButton.hidden = YES;
       self.tipView.hidden = NO;
      self.navigationBar.rightBarButton.hidden = NO;
   } else {
        self.sendMessageButton.hidden = YES;
        self.applyAddButton.hidden = YES;
    }
    
    [[SDWebImageManager sharedManager] loadImageWithURL:model.avatar.URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (image) {
            self.avatarImageView.image = image;
        }
    }];
        
    self.nicknameLabel.text = model.nickname;
    self.userIdLabel.text = [NSString stringWithFormat:@"UID: %@", model.uid];
    if (isEmptyString(model.brief)) {
        self.signatureLabel.text = @"what's up:";
    } else {
        self.signatureLabel.attributedText = [model.brief titleMargin:3 alignment:NSTextAlignmentLeft];
    }
    
   if (model.gender == 1) {
        self.genderImageView.image = [UIImage imageNamed:@"male_icon"];
        self.genderImageView.hidden = NO;
    } else if (model.gender == 2) {
        self.genderImageView.image = [UIImage imageNamed:@"female_icon"];
        self.genderImageView.hidden = NO;
    } else {
        self.genderImageView.hidden = YES;
    }
    
    if (isEmptyString(model.region)) {
        _locationLabel.hidden = YES;
        [_nicknameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarImageView).offset(10);
            make.left.equalTo(self.avatarImageView.mas_right).offset(10);
            make.right.mas_lessThanOrEqualTo(-leftRightMargin);
        }];
    } else {
        _locationLabel.hidden = NO;
        [_nicknameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarImageView).offset(-4);
            make.left.equalTo(self.avatarImageView.mas_right).offset(10);
            make.right.mas_lessThanOrEqualTo(-leftRightMargin);
        }];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@ ", model.region] attributes:@{
            NSFontAttributeName: _locationLabel.font,
        }];
        NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
        textAttachment.image = [UIImage imageNamed:@"userInfo_location"];
        textAttachment.bounds = CGRectMake(0, -3, textAttachment.image.size.width, textAttachment.image.size.height);
        NSAttributedString *iconAtt = [NSAttributedString attributedStringWithAttachment:textAttachment];
        [attributedString insertAttributedString:iconAtt atIndex:0];
        _locationLabel.attributedText = attributedString;
    }

}

- (void)loadDataIsNetwork:(BOOL)isNetwork isCache:(BOOL)isCache {
   
    NSString *userId = toString(_userId);
    
    if (isCache) {
        [HJIM.shareIM.userManager queryUserInfoWithUserId:userId complete:^(HJChatUserModel * _Nullable model) {
            [self handleUserData:model];
            if (isNetwork) {
                [HJIM.shareIM.userManager loadUserInfoWithUserId:userId complete:^(HJChatUserModel * _Nullable networkModel) {
                    if (!([model.nickname isEqualToString:networkModel.nickname] && [model.avatar isEqualToString:networkModel.avatar])) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:userInfoChangeNotification object:networkModel];
                        NSLog(@"userInfoChangeNotification");
                    }
                    [self handleUserData:networkModel];
                }];
            }
        }];
    } else {
        [HJIM.shareIM.userManager loadUserInfoWithUserId:userId complete:^(HJChatUserModel * _Nullable model) {
            [self handleUserData:model];
        }];
    }
}

- (void)dealloc {
    if (self.popBlock) {
        self.popBlock();
    }
}

@end
